package com.fount4j.generator.introspector.extend;

import com.fount4j.generator.context.GeneratorContext;
import com.fount4j.generator.exception.ConnectException;
import com.fount4j.generator.introspector.DataSourceIntrospector;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC 连接数据库
 *
 * @author Morven 2017/1/5
 */
public class JdbcDataSourceIntrospector extends DataSourceIntrospector {
    /** JDBC 驱动类 */
    private String driverClass;
    /** JDBC URL */
    private String url;
    /** 数据库用户 */
    private String user;
    /** 数据库密码 */
    private String password;

    @Override
    public Connection getConnection(GeneratorContext context) {
        Class<?> clazz;
        try {
            ClassLoader classLoader = context.getClassLoader();
            Class.forName(this.driverClass, true, classLoader);
            clazz = classLoader.loadClass(this.driverClass);
            Driver driver = (Driver) clazz.newInstance();
            Properties properties = new Properties();
            properties.put("user", this.user);
            properties.put("password", this.password);
            properties.putAll(this.getProperties());
            return driver.connect(this.url, properties);
        } catch (ClassNotFoundException e) {
            throw new ConnectException("数据库驱动类没有找到", e);
        } catch (SQLException | InstantiationException | IllegalAccessException e) {
            throw new ConnectException("连接数据库出错", e);
        }
    }

    public String getDriverClass() {
        return driverClass;
    }

    public void setDriverClass(String driverClass) {
        this.driverClass = driverClass;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
